package org.bronycorps.mlptss.domain.layer;

import java.util.ArrayList;
import java.util.List;

import org.bronycorps.mlptss.manager.CommonAssetManager;
import org.bronycorps.mlptss.manager.preferences.GameConfiguration;
import org.bronycorps.mlptss.manager.preferences.ModConfiguration.AnimatedBackgroundConfig;
import org.bronycorps.mlptss.manager.preferences.ModConfiguration.BackgroundConfig;
import org.bronycorps.mlptss.utils.BackgroundSprite;

import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.Texture.TextureWrap;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;

public class BackgroundLayer extends AbstractLayer {

	private final class Element {
		float speed;
		BackgroundSprite sprite;

		public Element(BackgroundSprite img, float speed) {
			super();
			this.sprite = img;
			this.speed = speed;
		}

	}

	private List<Element> elements = new ArrayList<BackgroundLayer.Element>();

	private CommonAssetManager manager;

	private Float speed = 1f;

	public BackgroundLayer() {
		super();

		this.manager = CommonAssetManager.getInstance();

		GameConfiguration config = GameConfiguration.getInstance();

		AnimatedBackgroundConfig background = config.getCurrentMod()
				.getBackgrounds().get(0);
		for (BackgroundConfig bgConf : background.getBackgrounds()) {
			String path = config.convertPath(bgConf.getPath());
			addBackgroundImage(path, bgConf.getOffset(), bgConf.getSpeed());
		}
	}

	@Override
	public void act(float delta) {
		super.act(delta);
		for (Element element : this.elements) {
			element.sprite.act(delta);
		}
	}

	private void addBackgroundImage(String path, float offset, float speed) {
		Texture texture = this.manager.get(path, Texture.class);
		texture.setWrap(TextureWrap.Repeat, TextureWrap.ClampToEdge);

		BackgroundSprite sprite = new BackgroundSprite(texture, speed,
				this.speed);
		sprite.setY(offset);

		this.elements.add(new Element(sprite, speed));
	}

	@Override
	public void draw(SpriteBatch batch, float parentAlpha) {
		for (Element element : this.elements) {
			element.sprite.setMainSpeed(this.speed);
			element.sprite.draw(batch, parentAlpha);
		}

	}

}
